package src.预编译;


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

public class MyHandleDBNice {
    public Connection connection;

    public MyHandleDBNice() throws Exception {
        this.conn();
    }
    /*
        获得德鲁伊数据池连接对象
         */
    public void conn() throws Exception {
        Properties properties = new Properties();
        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\86150\\IdeaProjects\\jdbc\\src\\预编译\\DruidJdbc.properties");
        properties.load(fileInputStream);

        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
    }

    //1.查询所有数据
    public ArrayList<Brand> findAllDate(String sql) throws SQLException {
        ArrayList<Brand> brands;
            PreparedStatement statement = connection.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();
            brands = new ArrayList<>();
            while (resultSet.next()) {
                Brand brand = new Brand();
                brand.setId(resultSet.getInt("id"));
                brand.setBrandName(resultSet.getString("brand_name"));
                brand.setCompanyName(resultSet.getString("company_name"));
                brand.setOrdered(resultSet.getString("ordered"));
                brand.setDes(resultSet.getString("description"));
                brand.setStatus(resultSet.getString("status"));
                brands.add(brand);
            }
        return brands;
    }
    public int insert(Brand brand) throws SQLException {
        String sql = "insert into tb_brand values(null,?,?,?,?,?)";
        PreparedStatement prestatement = connection.prepareStatement(sql);
        prestatement.setString(1, brand.getBrandName());
        prestatement.setString(2, brand.getCompanyName());
        prestatement.setString(3, brand.getOrdered());
        prestatement.setString(4, brand.getDes());
        prestatement.setString(5, brand.getStatus());
        int i = prestatement.executeUpdate();
        return i;
    }
    public static void main(String[] args) throws Exception {
        MyHandleDBNice myHandleDBNice = new MyHandleDBNice();
        System.out.println("myHandleDBNice.connection = " + myHandleDBNice.connection);
        ArrayList<Brand> allData = myHandleDBNice.findAllDate("select * from tbl_jdbc0");
        System.out.println("allData = " + allData);
        Brand brand1 = new Brand(5, "python", "文理", "1", "课程设计", "1");
        int insert = myHandleDBNice.insert(brand1);
        System.out.println("插入了 = " + insert+"条数据");
    }
}
